<?php
/**
 *@author sparkguo 
 *@date 2017-09-22   bonanza订单下载抓取
 */
defined('BASEPATH') OR exit('No direct script access allowed');
ini_set('max_execution_time', '0');
class taobaoapi extends CI_Controller {
    
    public $tabaoApiUrl='https://eco.taobao.com/router/rest';
    
	function __construct(){
		parent::__construct();
		$this->load->model('Function_m','fun');
		$this->pageSize =$this->config->item('pagenum');
        $this->load->model('Bonanzaapi_m','m');
    } 
    
    public function request(){
        $action = $other = $this->input->get_post('op');
		switch($action){
			case "jsonGetToken":
                $this->jsonGetToken();
				break; 
			case "getShopAuth":
                $this->getShopAuth();
                break; 
			case "saveAuth":
                $this->saveAuth();  
            break;
            case "getsku":
				$this->getApiGoodInfo();
			break; 
            case "complateOrders":
                $this->setOrderShipment();
            break;
		}
    }
    
    //远程返回数据
    public function getOrderDeliveryInfo(){
        $tid = $this->input->post_get('tid');
        
        $tid_arrs=explode(",",$tid);
        $tids=implode("','",$tid_arrs);
        $orderlist=$this->fun->getdatabaseslist("db_order_list"," and tradeid in('$tids')");
        $have_tids=iarray_column($orderlist,'tradeid');
        foreach($tid_arrs as $key=>$tid){//抓取没有抓取下来的订单
            if(!in_array($tid,$have_tids)){
                $orderDetail=$this->getTBorderDetail($tid);     
            }
        }
        $orderlist=$this->fun->getdatabaseslist("db_order_list"," and tradeid in('$tids')","consignee,address,mobile,goods_originask,tradeid");
        $json_data=json_encode($orderlist);
        
        echo $json_data;
    }
    
    //接收用户信息存储并 发货
    public function deliveryorder($tids){
        $tids='134104093730584123,121290149937203053';
        $url="http://120.27.131.51/taobaoapi/getOrderDeliveryInfo";
        $strParam = 'tid='.$tids;
        $headers = array(
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);
        $result =$this->tbHttpRequest($url,$headers,$strParam);
        $orderdata=json_decode($result,true);
        dump($orderdata);
        foreach($orderdata as $key=>$orderinfo){
            $upinfo=array('consignee'=>$orderinfo['consignee'],"address"=>$orderinfo['address'],"mobile"=>$orderinfo['mobile']);
            $this->db->update('db_order_list',$upinfo, " tradeid='".$orderinfo['tradeid']."'");
        }
        echo $result;
    }
        

    function getTaoBaoNewOrders(){
        $apiUrl=$this->tabaoApiUrl;
        $authcode= $this->fun->getdatabasesdetail("db_taobao_config");
        $nowpage = $_GET["pageid"];
        $totalpage=$_GET['totalpage'];
        $appKey = '24779813';
        $appSecret = 'b77e085f743aeb5a86d0b168e8d1bac5';
        $access_token= $authcode['access_token'];
        if ($nowpage == "") $nowpage = 1;
        //参数数组
        $paramArr = array(
             'app_key' => $appKey,
             'method' => 'taobao.trades.sold.increment.get',//taobao.trades.sold.get taobao.trades.sold.increment.get增量订单一天内
             'session'=>$access_token,
             'format' => 'json',
             'v' => '2.0',
             'sign_method'=>'md5',
             'timestamp' => date('Y-m-d H:i:s'),
             'status'=>'WAIT_SELLER_SEND_GOODS',
             'fields' => 'tid,type,status,payment',
             'page_size'=>40,
             //'sign' => 'sandbox_c_1'
        );
        $paramArr['start_modified']=date('Y-m-d H:i:s',strtotime('-23 hour'));
        $paramArr['end_modified']=date('Y-m-d H:i:s');
        echo $paramArr['start_modified']." 至 ".$paramArr['end_modified']."<br>"; 
        if($totalpage==''){
            $paramArr['use_has_next']=false;
        }else{
            $paramArr['use_has_next']='true';
        }
        $paramArr['page_no']=$nowpage;
        
         
        //生成签名
        $sign = $this->m->createSign($paramArr,$appSecret);
        $strParam = $this->m->createStrParam($paramArr);
        $strParam .= 'sign='.$sign;
        
        $headers = array(
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);
        $result =$this->tbHttpRequest($apiUrl,$headers,$strParam);
        //echo $result;
        $result_data=json_decode($result,true);
        //dump($result_data);
        if($result_data['trades_sold_increment_get_response']>0){//有返回
            if($totalpage=='' && $result_data['trades_sold_increment_get_response']['total_results']>0){
                $totalpage=ceil($result_data['trades_sold_increment_get_response']['total_results'] / $paramArr['page_size']);
            }
            
            $order_list=$result_data['trades_sold_increment_get_response']['trades']['trade'];
            $shopinfo = $this->fun->getdatabasesdetail("d_shop"," AND name='COSMORE'");
            if(empty($order_list)){$order_list=array();}
            $order_sns=array();
            foreach($order_list as $key=>$rs){
                $rs_order= $this->fun->getdatabasesdetail("db_order_list"," and tradeid='$rs[tid]'");

				if($rs_order['order_id']!=''){
					continue;
                    echo "$rs[tid] continue<br />";
				}
                $orderDetail=$this->getTBorderDetail($rs['tid']);
                $orderDetail['shopid']=$shopinfo['id'];
                $orderDetail['shopname']=$shopinfo['name'];
                $orderDetail['shopoper']=$shopinfo['updateoper'];  
                $order_sns[]=$this->addTaobaoOrder($orderDetail); 
            }
            //dump($order_sns);
            if(count($order_sns)>0){
                $order_sn_str=implode(',',$order_sns);
                dump($order_sn_str);
                $this->m->getTaobaoDeliveryInfo($order_sn_str);
            }
            
            $next_page=$nowpage+1;
            echo $next_page;
            echo $totalpage;
            if($next_page<=$totalpage){
                $request_order_url="/taobaoapi/getTaoBaoNewOrders?pageid=$next_page&totalpage=$totalpage";
                echo "<meta http-equiv=\"refresh\" content=\"1; url=$request_order_url \">";
            }else{
                echo "<br /><strong>本次订单已经同步完成</strong>";
            }
        }else{
            dump($result_data);
        }
        //同步交运信息至线上
        $this->setTrackingNumber();
    }
    
    //更新淘宝发货信息
    public function shipmentSend(){
        $apiUrl=$this->tabaoApiUrl;
        $authcode= $this->fun->getdatabasesdetail("db_taobao_config");
        $appKey = '24779813';
        $appSecret = 'b77e085f743aeb5a86d0b168e8d1bac5';
        $access_token= $authcode['access_token'];
        //参数数组
        $paramArr = array(
             'app_key' => $appKey,
             'method' => 'taobao.logistics.online.send',//在线订单发货处理
             'session'=>$access_token,
             'tid'=>$tid,
             'format' => 'json',
             'v' => '2.0',
             'sign_method'=>'md5',
             'timestamp' => date('Y-m-d H:i:s'),
             'fields' => 'payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_city,receiver_address,receiver_zip,receiver_mobile,receiver_phone,received_payment,receiver_country,receiver_town,tid,tid_str,num,status,type,price,
             total_fee,created,pay_time,buyer_message,seller_memo,invoice_name,nvoice_type,buyer_nick,shipping_type,receiver_district,orders',
        );
        //生成签名
        $sign = $this->m->createSign($paramArr,$appSecret);
        $strParam = $this->m->createStrParam($paramArr);
        $strParam .= 'sign='.$sign;
        $headers = array(
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);
        $result =$this->tbHttpRequest($apiUrl,$headers,$strParam);
        echo($result);
        $result_data=json_decode($result,true);
        $order_data=$result_data['trade_fullinfo_get_response']['trade'];
        return $order_data;
    }
    
    public function getTBorderDetail($tid){
        $apiUrl=$this->tabaoApiUrl;
        $authcode= $this->fun->getdatabasesdetail("db_taobao_config");
        $appKey = '24779813';
        $appSecret = 'b77e085f743aeb5a86d0b168e8d1bac5';
        $access_token= $authcode['access_token'];
        //参数数组
        $paramArr = array(
             'app_key' => $appKey,
             'method' => 'taobao.trade.fullinfo.get',//taobao.trades.sold.increment.get增量订单一天内
             'session'=>$access_token,
             'tid'=>$tid,
             'format' => 'json',
             'v' => '2.0',
             'sign_method'=>'md5',
             'timestamp' => date('Y-m-d H:i:s'),
             'fields' => 'payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_city,receiver_address,receiver_zip,receiver_mobile,receiver_phone,received_payment,receiver_country,receiver_town,tid,tid_str,num,status,type,price,
             total_fee,created,pay_time,buyer_message,seller_memo,invoice_name,nvoice_type,buyer_nick,shipping_type,receiver_district,orders',
        );
        //生成签名
        $sign = $this->m->createSign($paramArr,$appSecret);
        $strParam = $this->m->createStrParam($paramArr);
        $strParam .= 'sign='.$sign;
        $headers = array(
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);
        $result =$this->tbHttpRequest($apiUrl,$headers,$strParam);
        $result_data=json_decode($result,true);
        $order_data=$result_data['trade_fullinfo_get_response']['trade'];
        return $order_data;
    }
    
    public function addTaobaoOrder($dinfo){
        $arr_order_list=array();
        $v=$rs['order'];
        $buy_goods=$dinfo['orders']['order'];
        $country_code='CN';
        //获取国家名称与信息
		$countryinfo = $this->fun->getdatabasesdetail("d_country"," AND countryid='".$country_code."'");
        //汇率
        $exchange=$this->db->get_where("d_moneyrate","name='RMB'")->result_array();
        $dinfo['receiver_phone']=empty($dinfo['receiver_phone'])?"":$dinfo['receiver_phone'];
		$exchangerate=$exchange[0]["rate"];
		$arr_order_list['order_sn'] = $this->getNo();//生成订单序号
		$arr_order_list['dates']  = date("Y-m-d"); //当天日期 判断order_sn使用
		$arr_order_list['ordertime']  = $dinfo['created']; //订单日期时间
		$arr_order_list['order_source']  = "正常订单"; //默认
		$arr_order_list['customerid']  = $dinfo['buyer_nick']; //客户id
		$arr_order_list['consignee']  =$dinfo['receiver_name']; //收货人 consignee
		$arr_order_list['country']  = 'china';
		$arr_order_list['country_code']  = 'CN'; //国家
		$arr_order_list['country_cn']  = "中国"; //国家英文
        
        $arr_order_list['shipping_id']  = 25;
        $arr_order_list['shipping_name']  = '中通快递';
		$arr_order_list['province']  = $dinfo['receiver_state'];
		$arr_order_list['city']  = $dinfo['receiver_city'];
		$arr_order_list['address']  = $dinfo["receiver_district"]." ".$dinfo["receiver_address"];
		//$arr_order_list['address2']  = $v['address2'];
		$arr_order_list['zipcode']  = $dinfo['receiver_zip'];
		$arr_order_list['tel']  = $dinfo['receiver_phone'];//平台无电话
		$arr_order_list['mobile']  = $dinfo['receiver_mobile'];
		$arr_order_list['shopid']  = $dinfo['shopid']; //店铺id--------------
		$arr_order_list['shopname']  = $dinfo['shopname'];
		$arr_order_list['shopoper']  = $dinfo['shopoper'];//店铺负责人
       	
        
		$arr_order_list['moneytype']  = 'RMB';//货币类型
		$arr_order_list['tradeid']  = $dinfo['tid']; //交易单号
		$arr_order_list['goods_originask']  = $dinfo['payment']; //订单金额
		$arr_order_list['goods_amount']  = $dinfo['payment'];
        
		$arr_order_list['shipping_originask']  =$dinfo['post_fee']; //原始快递费
		$arr_order_list['shipping_fee']  =$arr_order_list['shipping_originask']*$exchangerate; //物流费 人民币
		
		$arr_order_list['pay_fee']  =0;//$arr_order_list['goods_amount'] * 0.015; //支付费用
        //$arr_order_list['email'] = $transinfo['buyer']['email']; //
		$arr_order_list['platform_fee']  = $dinfo['payment']*$exchangerate*0.05; //平台费用
		$arr_order_list['add_time'] = time();
		$arr_order_list['saleschannel']  = 'Tmall';
        $arr_order_list['platformID']  = 6;//
        $arr_order_list['moneyrate']  = $exchangerate;//当前汇率
        
		$arr_order_list['order_status']  = 2; //已支付
        //$arr_order_list['payid']  = $transinfo['providerID'];
        if(is_numeric($arr_order_list['address'])){
            $arr_order_list['order_status']  = 7; //待审核    
            $arr_order_list['remark']="收货地址异常：街道全是数字";
        }

		//留言
		if($dinfo['buyer_message']){
			$arr_order_list['platform_message']  = $dinfo['buyer_message']; //买家备注
		}
        if($dinfo['seller_memo']){
            $arr_order_list['remark']  = $dinfo['seller_memo']; //卖家备注   
        }
 	    
       // dump($arr_order_list);
		$this->db->trans_begin();	//事务开始
		$this->db->insert('db_order_list',$arr_order_list);
        echo $this->db->last_query();
		$insert_id = $this->db->insert_id(); //也就是db_order_sell 中order_id
		//更新日志记录
		$imgdata["goods_id"] = $insert_id;	//订单ID db_order_list
		$imgdata["updatetime"] = date("Y-m-d H:i:s");
		$imgdata["createUid"] = 0;
		$imgdata["types"] = 3;
		$imgdata["content"] = '天猫接口新增订单,交易ID='.$dinfo['tid'];
		$imgdata["createUser"] ='auto';
		$this->db->insert('db_goods_log', $imgdata);
        //echo $this->db->last_query();

        //卖出物品信息存入
		$error_flag =0;
        $weighttotal=0;
        $count_price=0;
		foreach($buy_goods as $key=>$value){
		    $goodsinfo=$value;
			$arr_order_sell['order_id'] = $insert_id;
            $arr_order_sell['goods_weight']=0;
            $goodsinfo['sku']=$goodsinfo["outer_sku_id"];
            $goodsinfo['sku']=$goodsinfo['sku']==''?$goodsinfo['outer_iid']:$goodsinfo['sku'];
            if(empty($goodsinfo['sku'])){
			    $arr_order_sell['goods_id'] = 0;
                $error_flag=1;
            }else{
                $rgoods = $this->fun->getdatabasesdetail("db_goods"," and goods_sku='".$goodsinfo['sku']."'");    
                if($rgoods){
                    $goodsinfo['sku']=$rgoods['goods_sku'];
                    $costprice=$this->fun->get_Goods_costprice($goodsinfo['sku']);
                }
                if($rgoods["goods_id"]==null){
                    $error_flag=1;
                }
                
                $rgoods["goods_id"]=$rgoods["goods_id"]==null?0:$rgoods["goods_id"];
                $arr_order_sell['goods_id']=$rgoods["goods_id"];
                $arr_order_sell['costprice'] = empty($costprice)?'':$costprice;//物品成本价
                $rgoods["g_weight"]=$rgoods["g_weight"]==null?0:$rgoods["g_weight"];
                $weight = $rgoods["g_weight"];
                $arr_order_sell['goods_weight'] = $weight;//毛重
                $weighttotal+=$weight;
            } 
            if($key+1>=count($buy_goods)){
                $goodsinfo['price']=$goodsinfo['payment']/$goodsinfo['num'];      
            }else{
                $count_price+=$goodsinfo['price'];  
            }
                
            $goodsinfo['sku']=empty($goodsinfo['sku'])?'':$goodsinfo['sku'];
            $arr_order_sell['goods_name'] = $goodsinfo['title'];

           
            $arr_order_sell['goods_sn'] = $goodsinfo['sku'];
            $arr_order_sell['sale_remark']=$goodsinfo['sku_properties_name'];
			$arr_order_sell['goods_number'] = $goodsinfo['num']; //商品数量
			$arr_order_sell['originsellprice'] = $goodsinfo['price'];
            $arr_order_sell['goods_price'] = $goodsinfo['payment']/$goodsinfo['num'];
            $arr_order_sell['originsku'] = $goodsinfo['outer_iid'];//原始sku
            $arr_order_sell['originsku']=$arr_order_sell['originsku']==null?'':$arr_order_sell['originsku'];
			$arr_order_sell['goods_amount'] =$goodsinfo['payment'];
			$this->db->insert('db_order_sell',$arr_order_sell);
            echo $this->db->last_query()."<br />";
			$insert_sell_id = $this->db->insert_id(); //也就是db_order_sell 中order_id

		}
        echo'成功导入一条订单'.$arr_order_list['order_sn'].' --tradeid:'.$arr_order_list['tradeid'].'<br />';
		if($error_flag || $arr_order_sell['goods_weight']>0 ){
			$this->db->where('order_id',$insert_id);
            if($error_flag){
                $data['order_status'] = 7;    
            }
			$data['orderweight'] = $weighttotal;
			$this->db->update('db_order_list',$data);
		}
		//若执行成功，则提交
		if ($this->db->trans_status() === FALSE){
			$this->db->trans_rollback();
		}else{
			$this->db->trans_commit();
		}
        return $arr_order_list['order_sn'];
    }
    
	public  function getNo() {
		$randCode = $this->randCode(5,1);
		$ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
		$order  = $this->db->get_where("db_order_list","order_sn ='".$ors."'")->result_array();
		if(count($order)>0)	//如果存在，则自动生成一个无序订单号
		{
			return $this->getNo();
		}else{
			return $ors;
		}
    }
    
	function randCode($length, $type = 0) {
		if($length ==999)
		{
			$length=mt_rand(3,10);
		}
		$arr = array(1 => "123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
		if ($type == 0) {
			array_pop($arr);
			$string = implode("", $arr);
		} elseif ($type == "-1") {
			$string = implode("", $arr);
		} else {
			$string = $arr[$type];
		}
		$count = strlen($string) - 1;
		$code = '';
		for ($i = 0; $i < $length; $i++) {
			$code .= $string[rand(0, $count)];
		}
		return $code;
	}
    
    public function getTaobaoAuth(){
        $auth_code=$_GET['code'];
        if(!empty($auth_code)){
            $adddata=array('auth_code'=>$auth_code,'createtime'=>date("Y-m-d H:i:s"),);
            $this->db->update('db_taobao_config',$adddata,'id>1');
            echo '授权信息更新成功';
        }else{
            $app_key='24779813';
            $url="https://oauth.taobao.com/authorize?response_type=code&client_id=$app_key&redirect_uri=http://www.erp.com/bonanzaapi/getTaobaoAuth";
            echo $url;
            redirect($url);    
        }
    }
    
    public function getAccessToken(){
        header("Content-Type:text/html;charset=UTF-8");
        $authcode= $this->fun->getdatabasesdetail("db_taobao_config");
        $appKey = '24779813';
        $appSecret = 'b77e085f743aeb5a86d0b168e8d1bac5';
        $code= $authcode['auth_code'];
        dump($code);
        //参数数组
        $paramArr = array(
             'app_key' => $appKey,
             'code' => $code,
             'client_id'=>$appKey,
             'client_secret'=>$code,
             'method' => 'taobao.top.auth.token.create',
             'format' => 'json',
             'v' => '2.0',
             'sign_method'=>'md5',
             'timestamp' => date('Y-m-d H:i:s'),
             'fields' => 'nick,type,user_id',
             'grant_type'=>'authorization_code',
             //'sign' => 'sandbox_c_1'
        );
        dump($paramArr);
        //生成签名
        $sign = $this->m->createSign($paramArr,$appSecret);
        //$paramArr['sign']=$sign;
        //组织参数
        $strParam = $this->m->createStrParam($paramArr);
        $strParam .= 'sign='.$sign;
        //访问服务
        $url = 'https://eco.taobao.com/router/rest'; //https://oauth.tbsandbox.com/token 沙箱环境调用地址
                
        echo $strParam;
        $headers = array(
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);
        $result =$this->tbHttpRequest($url,$headers,$strParam);
        $result_data=json_decode($result,true);
        dump($result_data);
        $token_info=json_decode($result_data['top_auth_token_create_response']['token_result'],true);
        dump($token_info);
        echo "json的结构为:";
        print_r($result);
        if($token_info['expire_time']){
            $expire_time=$this->microtime_format('Y-m-d H:i:s',$token_info['expire_time']);
            $adddata=array('access_token'=>$token_info['access_token'],'token_expire_time'=>$expire_time,'access_token_detail'=>json_encode($token_info),);
            $this->db->update('db_taobao_config',$adddata,'id>1');
        }
    }
    
    function refreshToken(){
        header("Content-Type:text/html;charset=UTF-8");
        $authcode= $this->fun->getdatabasesdetail("db_taobao_config");
        dump($authcode);
        $token_detail=json_decode($authcode['access_token_detail'],true);
        dump($token_detail);
        $refresh_token=$token_detail['refresh_token'];
        dump($token_detail);
        $appKey = '24779813';
        $appSecret = 'b77e085f743aeb5a86d0b168e8d1bac5';
        //参数数组
        $paramArr = array(
             'app_key' => $appKey,
             'client_id'=>$appKey,
             'client_secret'=>$appSecret,
             'method' => 'taobao.top.auth.token.refresh',
             'format' => 'json',
             'grant_type'=>'refresh_token',
             'v' => '2.0',
             'refresh_token'=>$refresh_token,
             'sign_method'=>'md5',
             'timestamp' => date('Y-m-d H:i:s'),
        );
        dump($paramArr);
        //生成签名
        $sign = $this->m->createSign($paramArr,$appSecret);
        //组织参数
        $strParam = $this->m->createStrParam($paramArr);
        $strParam .= 'sign='.$sign;
        echo $strParam;
        echo "<br />";
        //访问服务
        $url = 'https://eco.taobao.com/router/rest'; //https://oauth.tbsandbox.com/token 沙箱环境调用地址
                
        echo $strParam;
        $tborder=1;
        $dev_name=1;
        $headers = array(
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);
        $result =$this->tbHttpRequest($url,$headers,$strParam);
        $result_data=json_decode($result,true);
        dump($result_data);
        $token_info=json_decode($result_data['top_auth_token_refresh_response']['token_result'],true);
        dump($token_info);
        echo "token刷新成功，json的结构为:";
        print_r($result);
        if($token_info['expire_time']){
            $expire_time=$this->microtime_format('Y-m-d H:i:s',$token_info['expire_time']);
            $adddata=array('access_token'=>$token_info['access_token'],'token_expire_time'=>$expire_time,'access_token_detail'=>$result,);
            $this->db->update('db_taobao_config',$adddata,'id>1');
        }
    }
    
    public function  setTrackingNumber(){
        $apiUrl=$this->tabaoApiUrl;
        $authcode= $this->fun->getdatabasesdetail("db_taobao_config");
        $appKey = '24779813';
        $appSecret = 'b77e085f743aeb5a86d0b168e8d1bac5';
        $access_token= $authcode['access_token'];
        //$order_id='128838902566873';
        //$where=" WHERE 1 ";
        $where = " WHERE (order_status = 4 or order_status = 5) AND is_update_platform in(0) "; //4为已发货状态 is_update_platform为未与线上同步
        $where .= " AND shipping_name is not null AND shipping_number is not null and shipping_time>='".strtotime('-4 day')."'";
        if($order_id){
            $where.=" AND order_sn = '{$order_id}' ";
        }
        $where.= " AND shopname='COSMORE'";
        $sql_mabangorder = "SELECT order_id,order_sn,shipping_name,shopid,tradeid,shipping_number FROM db_order_list ".$where;
        $rs_mabangorder = $this->db->query($sql_mabangorder)->result_array();
        //echo $sql_mabangorder;
        foreach($rs_mabangorder as $k=>$v){
            //参数数组
            $paramArr = array(
                 'app_key' => $appKey,
                 'method' => 'taobao.logistics.online.send',//taobao.trades.sold.increment.get增量订单一天内
                 'session'=>$access_token,
                 'tid'=>$v['tradeid'],
                 'format' => 'json',
                 'v' => '2.0',
                 'sign_method'=>'md5',
                 'timestamp' => date('Y-m-d H:i:s'),
                 'out_sid'=>$v['shipping_number'],
                 'company_code'=>'ZTO',
            );
            //生成签名
            $sign = $this->m->createSign($paramArr,$appSecret);
            $strParam = $this->m->createStrParam($paramArr);
            $strParam .= 'sign='.$sign;
            $headers = array(
            CURLOPT_SSL_VERIFYPEER=>false,
            CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);
            $result_json =$this->tbHttpRequest($apiUrl,$headers,$strParam);
   
            $result_data=json_decode($result_json,true);
            if($result_data['logistics_online_send_response']['shipping']['is_success']==true){
                $this->db->where('order_id',$v['order_id']);
                $arr_plat['is_update_platform']=1;
                $this->db->update('db_order_list',$arr_plat); //说明已经同步过
    
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $v['order_id'];	//订单ID db_order_list
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = 0;
                $imgdata["types"] = 3;
                $imgdata["content"] = '天猫接口同步交运信息至线上成功,交易ID='.$v['tradeid'];
                $imgdata["createUser"] ='auto';
                $this->db->insert('db_goods_log', $imgdata);
                //echo $this->db->last_query();
            }else{
                $this->db->where('order_id',$v['order_id']);
                $arr_plat['is_update_platform']=4;
                $this->db->update('db_order_list',$arr_plat); //说明已经同步过
                echo"订单 ".$v['tradeid'].' 更新线上交运信息失败，失败原因：'.$result_json.'<br />';
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $v['order_id'];	//订单ID db_order_list
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = 0;
                $imgdata["types"] = 3;
                $imgdata["content"] = '天猫接口同步交运信息至线上失败,失败原因：'.$result_json;
                $imgdata["createUser"] ='auto';
                $this->db->update("db_mabangorder", array("exememo" =>'线上发货失败，请手动同步'), "mailNo='".$v['shipping_number']."'");
                $this->db->insert('db_goods_log', $imgdata);
            }
        }
    }
    
    /** 格式化时间戳，精确到毫秒，x代表毫秒 */
    function microtime_format($tag, $time){
       list($usec, $sec) = explode(".", $time);
       $date = date($tag,$usec);
       return str_replace('x', $sec, $date);
    }
    
    
    function tbHttpRequest($url, $headers, $post_fields) {
        $args = array();
        $connection = curl_init($url);            
        $curl_options = array(CURLOPT_HTTPHEADER=>$headers, CURLOPT_POSTFIELDS=>$post_fields,
        CURLOPT_SSLVERSION=>CURL_SSLVERSION_TLSv1, 
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);  # data will be returned as a string
        curl_setopt_array($connection, $curl_options);
        $json_response = curl_exec($connection);
        if (curl_errno($connection) > 0) {
          echo curl_error($connection) . "\n";
          exit(2);
        }
        curl_close($connection);
        return $json_response;
    }
}
